<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'btn:order:flow:lastDate'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #flowList>
        <BasicTable @register="registerChildTable" @row-click="handleChildRowClick" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8OrderFlowFlowForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { M8OrderPic, updateLastDateForm, updateLastDateSave } from '/@/api/m8/order/order';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('m8.order.flow');
  const { showMessage } = useMessage();
  const record = ref<M8OrderPic>({} as M8OrderPic);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'simple-line-icons:calendar',
    value: t('批量指定流程截止日期'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('图名'),
      field: 'picname',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t('规格'),
      field: 'cinvstd',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      dynamicDisabled: true,
      required: false,
    },
    {
      label: t(''),
      field: 'flowList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'flowList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerChildTable, flowListTable] = useTable({
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: false,
  });

  async function setChildTableData(_res: Recordable) {
    flowListTable.setColumns([
      {
        title: t('顺序'),
        dataIndex: 'sortNum',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operCode',
        width: 80,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('工序名称'),
        dataIndex: 'oper.operName',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('状态'),
        dataIndex: 'flowStatus',
        width: 80,
        align: 'left',
        dictType: 'M8_order_status',
        editRow: false,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_menu_type',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('截止日期'),
        dataIndex: 'lastDate',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editable: true,
        editRule: false,
      },
      {
        title: t('完工日期'),
        dataIndex: 'overDate',
        width: 130,
        align: 'center',
        editRow: false,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
    ]);
    flowListTable.setTableData(record.value.flowList || []);
  }

  function handleChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of flowListTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of flowListTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      childList.push({
        ...record,
        status: '1',
      });
    }
    if (!childListValid) {
      throw { errorFields: [{ name: ['flowList'] }] };
    }
    return childList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await updateLastDateForm(data);
    record.value = (res.orderPic || {}) as M8OrderPic;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.flowList = await getChildList();
      // console.log('submit', params, data, record);
      const res = await updateLastDateSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
